<template>
  <div class="content">
    <div style="display: flex">
      <jc-button
        v-if="!fnumber"
        :btn-arr="['reload', 'sub', bomCost('save:Bom') && 'newy', 'option', 'pass', 'batchFill', 'remove']"
        :disab-arr="['close', 'cancel', 'copy', 'freeze', 'com1', 'com2']"
        url="tEngBom/queryTEngBomList"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @submit="submitBom(1)"
        @noSubmit="submitBom(2)"
        @refresh="handleQueryBomList"
        @newly="addBom"
        @del="delBom"
        @toExcel="handleExport"
        @startUsing="using(1)"
        @forbidden="using(2)"
      />
      <el-button style="margin-left: 10px;" size="mini" type="primary" @click="isSetingCorect=true">批改</el-button>
      <el-button style="margin-left: 10px" size="mini" type="primary" @click="excelVisab=true">导入Excel</el-button>
      <el-button style="margin-left: 10px" size="mini" type="primary" @click="mubanDeload">导出模板</el-button>
      <el-button
        style="margin-left: 10px"
        type="primary"
        size="mini"
        @click="dowloadBom"
      >
        导出树形BOM
      </el-button>
    </div>
    <div v-if="!fnumber" class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQueryBomList"
        />
        <el-button
          type="primary"
          class="btn"
          size="mini"
          @click="handleQueryBomList"
        >
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          :select-data="selectData"
          @seachData="handleQueryBomList"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        sortable
        :tooltip="false"
        table-selection
        @selectionChange="selectionDatas"
        @clickRow="bomSelect"
      >
        <template v-slot:billSlot="col">
          <el-image
            style="width: 30px;height: 30px;"
            :src="$img + col.scope.row.fimg"
            :preview-src-list="[$img + col.scope.row.fimg]"
          />
        </template>
        <template v-slot:text2Slot="col">
          <el-image
            style="width: 30px;height: 30px;"
            :src="$img + col.scope.row.img"
            :preview-src-list="[$img + col.scope.row.img]"
          />
        </template>
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row.fnumber)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <template v-slot:btnState="clo">
          <el-tag>{{ clo.scope.row.fdocumentstatus }}</el-tag>
        </template>
        <!--审核状态-->
        <template v-slot:btnStates="col">
          <span v-if="col.scope.row.fdocumentstatus===''" />
          <el-tag
            v-else
            :type="col.scope.row.stateColor"
          >
            {{ col.scope.row.fdocumentstatus }}
          </el-tag>
        </template>
        <!--禁用状态-->
        <template v-slot:tagSlot="clo">
          <el-tag v-if="clo.scope.row.fforbidstatus === $t('market.no')">
            {{ clo.scope.row.fforbidstatus }}
          </el-tag>
          <el-tag v-else type="danger">
            {{ clo.scope.row.fforbidstatus }}
          </el-tag>
        </template>
        <template v-slot:btnSlot="clo">
          <el-button
            v-if="false"
            size="mini"
            type="warning"
            @click="queryReportForm(clo.scope.row.fnumber)"
          >
            {{ $t('market.lookList') }}<!--查看报表-->
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="getIntoBom(clo.scope.row)"
          >
            {{ $t('market.intoBom') }}<!--进入bom-->
          </el-button>
        </template>
      </jc-table>
      <cardTab :tab-arr="tabArr" @search="handleQueryBomList1" />
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="handleGetBomList"
      />
    </div>
    <el-dialog
      v-dialogDrag
      title="导入Excel"
      :visible.sync="excelVisab"
      width="500px"
      top="5vh"
      center
    >
      <div style="text-align: center;">
        <el-upload
          class="upload-demo"
          drag
          :action="actionUrl + '/tEngBom/importBom'"
          multiple
          :show-file-list="false"
          :on-success="uploadSuccess"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">请上传excel文件</div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="excelVisab = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="excelVisab = false">
          {{ $t('btn.confirm') }}
        </el-button>
      </span>
    </el-dialog>
    <!--批改-->
    <setting v-if="isSetingCorect" :ftype="2" :fids="fids" @setting="isSetingCorect=false" />
  </div>
</template>

<script>
import {
  queryBomList,
  deleteBom,
  auditBom,
  unauditBom,
  auditBomList,
  unauditBomList,
  submitBomList,
  unsubmitBomList, exportBom
} from '@/api/engineering/bomList'
import { Forbid, toMxBmina } from '@/components/ToMxamineState'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
export default {
  name: 'ListBom',
  components: {
    setting: () => import('@/views/basic/material/materielList/setting'),
    cardTab: () => import('@/components/cardTab'),
    search,
    jcButton,
    filtration
  },
  mixins: [searData],
  props: {
    fnumber: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      excelVisab: false,
      isSetingCorect: false,
      fids: [],
      ftype: 13,
      fbillNo: 'fnumber', // 编码
      total: 0, // 总条目
      pageNum: 1, // 当前页
      pageSize: 200, // 每页显示多少条数据
      actionUrl: 'jc',
      // 表头
      tableHeader: [
        { label: this.$t('shop.image'), type: 'bill', prop: 'fimg', width: '80' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '120' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        {
          label: this.$t('shop.fspecificaTion'),
          prop: 'fspecification'
        },
        {
          label: this.$t('market.fdescripTion'),
          prop: 'fdescription',
          minWidth: '200px'
        },
        {
          label: this.$t('market.createDate'),
          prop: 'fcreatedate'
        },
        {
          label: this.$t('market.documentstatus'),
          prop: 'fdocumentstatus',
          type: 'states'
        },
        { label: this.$t('market.childModel1'), prop: 'MODEL', width: '120' },
        { label: this.$t('market.subitemNum'), prop: 'NUMBER', width: '120' },
        { label: this.$t('market.subitemName'), prop: 'name', width: '120' },
        { label: this.$t('market.childSpec'), prop: 'SPECIFICATION', width: '120' },
        { label: this.$t('market.childunit'), prop: 'unit' },
        { label: this.$t('market.materialType'), prop: 'ferpcls' },
        { label: this.$t('market.isskip'), prop: 'fisskip' },
        { label: this.$t('market.handle'), type: 'btn', width: '120' }
      ],
      // 表格数据
      tableData: [],
      tableHeader1: [
        { label: this.$t('market.forbidStatu'), type: 'tag', prop: 'FFORBIDSTATUS' },
        { label: this.$t('market.funit'), prop: 'funit' },
        { label: this.$t('market.creator'), prop: 'fcreator' },
        { label: this.$t('market.modifier'), prop: 'fmodifier' },
        { label: this.$t('market.modifyDate'), prop: 'fmodifydate' },
        { label: this.$t('market.approver'), prop: 'fapprover' },
        { label: this.$t('market.approveDate'), prop: 'fapprovedate' },
        { label: this.$t('market.fcraftname'), prop: 'fcraft' },
        { label: this.$t('market.childimg'), type: 'text2', prop: 'img' }
      ],
      tabArr: [
        { label: '成品', name: '1-' },
        { label: '半成品', name: '2-' },
        { label: '原材料', name: '3-' }
      ],
      image: '', // 图片
      age: 1,
      newAge: 5
    }
  },
  watch: {
    fnumber() {
      this.handleGetBomList()
    }
  },
  created() {
    const publicPath = location.pathname
    if (publicPath.indexOf('jc-web') !== -1) { // 惠州杰希
      this.actionUrl = '/jc'
    } else if (publicPath.indexOf('mlg-web') !== -1) { // 摩洛哥
      this.actionUrl = '/mlg'
    } else if (publicPath.indexOf('nx-web') !== -1) { // 惠州杰希内销
      this.actionUrl = '/nx'
    } else if (publicPath.indexOf('jnk-web') !== -1) { // jnk
      this.actionUrl = '/jnk'
    } else {
      this.actionUrl = location.origin
    }
    !this.fnumber && this.handleGetBomList()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          queryBomList({
            pageNum: 1,
            pageSize: 100000,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return (toMxBmina(item), Forbid(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, 'BOM清单')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 进入物料主数据
    jumpMateriel(FNUMBER) {
      this.$router.push({ path: `/detailMateriel/${FNUMBER}` })
    },
    // 获取列表数据
    async handleGetBomList(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        search: this.searCollData.concat(this.details)
      }
      if (this.fnumber) {
        DATA.fnumber = this.fnumber
        DATA.fforbidStatus = 'A' // 禁用: 否
        DATA.fdocumentStatus = 'C' // 已审核
      }
      const { data: RES } = await queryBomList(DATA)
      this.tableData = RES.array.map(item => {
        return (toMxBmina(item), Forbid(item))
      })
      this.total = RES.total
      this.loading = false
    },
    // 搜索
    handleQueryBomList(ev) {
      this.pageNum = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetBomList(ev.detail)
      } else {
        this.handleGetBomList()
      }
    },
    // 上传成功回调函数，
    uploadSuccess(res, file) {
      if (res.code === 0) { // 返回值为1表示上传成功
        this.$message({ showClose: true, message: res.message, type: 'success' })
      } else {
        this.$message({
          message: res.message,
          type: 'error'
        })
      }
    },
    // 成品 原材料
    handleQueryBomList1(ev) {
      this.searCollData = []
      this.pageNum = 1
      this.searCollData = ev
      this.searchSon = ev
      this.handleGetBomList()
    },
    // 跳转新建bom
    addBom() {
      this.$router.push({ path: `/treeBom/:FNUMBER` })
    },
    // 导出模板
    mubanDeload() {
      window.open('http://14.29.79.10:8808/jc/image/common/物料清单模板.xls')
    },
    // 查看报表
    queryReportForm(FNUMBER) {
      this.$router.push({ path: `/reportForm/${FNUMBER}` })
    },
    // 进入bom
    async getIntoBom(item) {
      const { fnumbercopy } = item
      this.$router.push({ path: `/treeBom/${fnumbercopy}` })
      // // 跳转bom树节点
      // if (FISDEFAULT === 1) {
      //   this.$router.push({ path: `/treeBom/${FNUMBER}` })
      // } else if (FISDEFAULT !== 1) {
      //   this.$router.push({ path: `/treeBom2/${FNUMBER}` })
      // }
    },
    // 导出树形BOM
    dowloadBom(ev) {
      const DATA = {
        fmaterialId: this.fmaterialid
      }
      exportBom(DATA).then(res => {
        if (res.code === 0) {
          this.treeBom = res.data
          this.handleExport1()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 多选时触发的事件
    selectionDatas(val) {
      this.selectVal = []
      this.fids = []
      this.fmaterialid = val[0].fmaterialid
      this.val = val
      if (val.length > 0) {
        val.forEach(res => {
          res.fnumber && this.selectVal.push(res.fnumber)
          this.fids.push(res.fentryid)
        })
      }
    },
    // MRP修改BOM版本返回值
    bomSelect(ev) {
      this.$emit('bom', ev)
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetBomList()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 删除BOM
    delBom() {
      this.$confirm('该操作将永久删除BOM，确定要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = deleteBom
        this.toExamineFun(api)
      })
    },
    // 提交
    async submitBom(ev) {
      const api = ev === 1 ? submitBomList : unsubmitBomList
      this.toExamineFun(api)
    },
    // 审批通过
    async audit(ev) {
      const api = ev === 1 ? auditBomList : unauditBomList
      this.toExamineFun(api)
    },
    // 启用、禁用
    async using(ev) {
      const api = ev === 1 ? auditBom : unauditBom
      this.toExamineFun(api)
    },
    // 导出树形BOM
    handleExport1() {
      require.ensure([], () => {
        const tHeader = ['BOM层级', '子项物料编码', '物料名称', '规格型号', '物料规格', '物料属性', '单位', '用量', '单价', '人工成本', '是否跳层', '操作人']
        const filterVal = ['BOM层级', '子项物料编码', '物料名称', '规格型号', '物料规格', '物料属性', '单位', '用量', '单价', '人工成本', '是否跳层', '操作人']
        if (this.treeBom.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          const list = this.treeBom
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '树形BOM')
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;
  .header {
    position: relative;
    .header-name {
      width: 100%;
    }
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
  .productImg {
    width: auto;
    height: 40px;
  }
  .el-dialog .el-dialog__body {
    text-align: center;
  }
  .image {
    width: auto;
    height: 100%;
    max-height: 100%;
    max-width: 100%;
  }
}
</style>
